package com.sctvcloud.qingchuan.ui.adapter.holder;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.beans.DeclareBean;
import com.sctvcloud.qingchuan.beans.FRebellion;
import com.sctvcloud.qingchuan.beans.ImageUr;
import com.sctvcloud.qingchuan.ui.activities.ApplyDetailActivity;
import com.sctvcloud.qingchuan.ui.activities.MyDeclareDetailActivity;
import com.sctvcloud.qingchuan.ui.adapter.PicAdapter;
import com.sctvcloud.qingchuan.ui.util.IListShowData;
import com.sctvcloud.qingchuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.qingchuan.ui.utils.GlideUtil;
import com.sctvcloud.qingchuan.ui.utils.ItemImagTarget;
import com.sctvcloud.qingchuan.ui.utils.UIUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sctvcloud.qingchuan.base.BaseActivity.DO_UP_POS;
import static com.sctvcloud.qingchuan.base.BaseActivity.EX_COMMENT_TYPE;
import static com.sctvcloud.qingchuan.base.BaseActivity.EX_DATA;

public class MyDeclareHolder extends BaseRebllionHolder {
    @BindView(R.id.item_rebllion_avatar)
    protected CustomEXImageView avatar;
    @BindView(R.id.item_rebllion_username)
    protected CustomFontTextView userName;
    @BindView(R.id.item_rebllion_time)
    protected CustomFontTextView time;
    //    @BindView(R.id.item_declare_pic_title)
//    protected TextView content;
    @BindView(R.id.item_declare_content)
    protected CustomFontTextView item_declare_content;

    @BindView(R.id.item_declare_pic_address)
    protected CustomFontTextView address;
    @BindView(R.id.item_declare_pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.item_declare_video_img)
    protected ImageView video_img;
    @BindView(R.id.item_declare_video_play)
    protected ImageView play;
    @BindView(R.id.item_achor_single_temp)
    protected View singleTemp;
    @BindView(R.id.item_declare_pic_fl)
    protected ViewGroup video_rl;
    @BindView(R.id.item_declare_pic_ll_four)
    protected ViewGroup four_ll;
    @BindView(R.id.item_declare_pic_img1)
    protected CustomEXImageView img1;
    @BindView(R.id.item_declare_pic_img2)
    protected CustomEXImageView img2;
    @BindView(R.id.item_declare_pic_img3)
    protected CustomEXImageView img3;
    @BindView(R.id.item_declare_pic_img4)
    protected CustomEXImageView img4;
    @BindView(R.id.item_declare_pic_img5)
    protected CustomEXImageView img5;
    @BindView(R.id.item_declare_pic_img6)
    protected CustomEXImageView img6;
    @BindView(R.id.tv_anchor_up_apply)
    public CustomFontTextView tv_anchor_up;
    @BindView(R.id.tv_comments_type)
    protected CustomFontTextView tv_comments_type;

    @BindView(R.id.tv_status)
    public CustomFontTextView tv_status;

    private GridLayoutManager manager;
    private PicAdapter adapter;

    private ItemImagTarget imgTarget;

    private DeclareBean declareBean;


    private ViewTreeObserver.OnGlobalLayoutListener singleGlobal = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (imgTarget != null && singleTemp.getWidth() > 0) {
                imgTarget.setMxW(singleTemp.getWidth());
                singleTemp.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    };

    private RequestListener<String, GlideDrawable> lis = new RequestListener<String, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            return false;
        }
    };
    private List<ImageUr> contentImage;


    public MyDeclareHolder(final Context context, View itemView) {
        super(context, itemView);

        imgTarget = new ItemImagTarget(video_img);
        singleTemp.getViewTreeObserver().addOnGlobalLayoutListener(singleGlobal);


        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MyDeclareDetailActivity.class);
                intent.putExtra(EX_DATA, declareBean);
                intent.putExtra(EX_COMMENT_TYPE, 4);
                intent.putExtra(DO_UP_POS, getAdapterPosition());
                context.startActivity(intent);

            }
        });

    }

    @Override
    public void onDestory() {
        super.onDestory();
    }

    @Override
    protected void initInject() {
        ButterKnife.bind(this, itemView);
    }


    @Override
    public void setData(IListShowData fr) {
        if (fr instanceof DeclareBean) {
            this.declareBean = (DeclareBean) fr;
            super.setData(declareBean);


            userName.setText(!TextUtils.isEmpty(declareBean.getUserName()) ? declareBean.getUserName() : "");


//            content.setText(Html.fromHtml("<font color=\"#01ACE4\">" + (TextUtils.isEmpty(declareBean.getTopic()) ? "" : declareBean.getTopic()) + "</font>" +
//                    "<strong><font color=\"#222222\">" + (TextUtils.isEmpty(declareBean.getDiscloseTitle()) ? "" : declareBean.getDiscloseTitle() + "</font></strong>")));
//            //time.setText(TextUtils.isEmpty(declareBean.getTime()) ? context.getString(R.string.default_time) : declareBean.getTime());

            item_declare_content.setText(TextUtils.isEmpty(declareBean.getContent()) ? "" : declareBean.getContent());
            if (TextUtils.isEmpty(declareBean.getContent())) {
                item_declare_content.setVisibility(View.GONE);
            } else {
                item_declare_content.setVisibility(View.VISIBLE);
            }
            JLog.e("------------MyDeclareHolder-----time-"+DateUtils.timeAgo(DateUtils.getDataDate(declareBean)));
            time.setText(TextUtils.isEmpty(declareBean.getCreateTime()) ? "" : DateUtils.timeAgo(DateUtils.getDataDate(declareBean)));
            if (TextUtils.isEmpty(declareBean.getLocation())) {
                address.setVisibility(View.GONE);
            } else {
                address.setVisibility(View.VISIBLE);
            }


            address.setText(TextUtils.isEmpty(declareBean.getLocation()) ? "" : declareBean.getLocation());
            if (!TextUtils.isEmpty(declareBean.getUserAvatar())) {
                //GlideUtil.loadAvatorDef(context, declareBean.getUserAvator(), avatar);
                GlideUtil.getGlid(context, declareBean.getUserAvatar()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).error(R.mipmap.icon_circle_avatar)
                        .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(context))
                        .into(avatar);
            } else {
                avatar.setImageResource(R.mipmap.icon_circle_avatar);
            }

            //0未处理，1处理中,2已处理

            if (declareBean.getStatus() == 1) {
                tv_status.setText(context.getResources().getText(R.string.tv_done));
                tv_status.setTextColor(context.getResources().getColor(R.color.color_09CEB4));
                tv_status.setVisibility(View.VISIBLE);
            } else if (declareBean.getStatus() == 0) {
                tv_status.setText(context.getResources().getText(R.string.tv_doing));
                tv_status.setTextColor(context.getResources().getColor(R.color.color_0087D8));
                tv_status.setVisibility(View.VISIBLE);
            } else {
                tv_status.setVisibility(View.GONE);
            }
            tv_anchor_up.setVisibility(View.GONE);

            if (TextUtils.isEmpty(declareBean.getVideoUrl())) {
                video_img.setVisibility(View.GONE);
                play.setVisibility(View.GONE);
                contentImage = declareBean.getImageList();
                if (ListUtils.isListValued(contentImage)) {
                    if (contentImage.size() == 1) {
                        pic_list.setVisibility(View.GONE);
                        video_rl.setVisibility(View.VISIBLE);
                        video_img.setVisibility(View.VISIBLE);
                        four_ll.setVisibility(View.GONE);
//                    GlideUtil.getGlideWithLarge169Def(context, contentImage.get(0).getImageUrl()).into(imgSingle);
//                    JLog.e("will show single img "+contentImage.get(0).getImageUrl()+"\n"+this+"   "+imgSingle.getVisibility()+"   "+video_rl.getVisibility());
//                        GlideUtil.getGlideWith11DefNoFit(context, contentImage.get(0).getImageUrl()).into(imgTarget);
                        initImgView(UrlUtils.linkUrls(Constances.ST_BASE_URL,contentImage.get(0).getImageUrl()));
                    } else if (contentImage.size() == 4) {
                        pic_list.setVisibility(View.GONE);
                        video_rl.setVisibility(View.GONE);
                        four_ll.setVisibility(View.VISIBLE);
                        GlideUtil.loadImgWith11Def(context, contentImage.get(0).getImageUrl(), img1);
                        GlideUtil.loadImgWith11Def(context, contentImage.get(1).getImageUrl(), img2);
                        GlideUtil.loadImgWith11Def(context, contentImage.get(2).getImageUrl(), img4);
                        GlideUtil.loadImgWith11Def(context, contentImage.get(3).getImageUrl(), img5);
                        img3.setImageDrawable(null);
                        img6.setImageDrawable(null);
                    } else {
                        initView(contentImage);
                        pic_list.setVisibility(View.VISIBLE);
                        video_rl.setVisibility(View.GONE);
                        four_ll.setVisibility(View.GONE);
                    }
                } else {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.GONE);
                }
            } else {
                pic_list.setVisibility(View.GONE);
                video_img.setVisibility(View.VISIBLE);
//            imgSingle.setVisibility(View.GONE);
                video_rl.setVisibility(View.VISIBLE);
                play.setVisibility(View.VISIBLE);
                four_ll.setVisibility(View.GONE);
                String coverImageUrl = declareBean.getCoverImage();
//                GlideUtil.getGlideWith11DefNoFit(context, coverImageUrl).into(imgTarget);
                initImgView(UrlUtils.linkUrls(Constances.ST_BASE_URL,coverImageUrl));
            }
        }
    }

    @OnClick({R.id.item_declare_video_play, R.id.tv_anchor_up_apply})
    public void itemClick(View view) {
        switch (view.getId()) {
            case R.id.item_declare_video_play:
                if (internalClick != null) {
                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
                }
                break;
//            case R.id.tv_anchor_up_apply:
//                if (internalClick != null) {
//                    internalClick.onItemInternalClick(itemView, view, getAdapterPosition());
//                }

//                break;

        }
    }


//    private void doUp(final ADynamicsItem aDynamicsItem) {
//        ParamsEditor pe = new ParamsEditor();
////        HashMap<String, Object> param = new HashMap<>();
//        pe.put("dynamicId", aDynamicsItem.getDynamicId());
////        pe.put("token", UserManager.getInstance().getToken());
//        pe.put("userId", UserManager.getInstance().getUser().getUserId());
//
//        NetUtils.getNetAdapter().doUpForDynamics(context.getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
//            @Override
//            public void onSuc(SingleResult singleResult) {
//                if (singleResult.isSuccess()) {
//                    SkipUtil.skipToAddUserOperate(context, getOwnerName(),  13, 2, "主播圈点赞", aDynamicsItem.getDynamicId(), Cache.getInstance().getCurrentChannelId());
//                    for (ADynamicsItem item : dyDatas) {
//                        if (item.getDynamicId().equals(aDynamicsItem.getDynamicId())) {
//                            item.setAttitudesCount(aDynamicsItem.getAttitudesStatus() ? aDynamicsItem.getAttitudesCount() - 1 : aDynamicsItem.getAttitudesCount() + 1);
//                            item.setAttitudesStatus(!aDynamicsItem.getAttitudesStatus());
//                            adapter.notifyDataSetChanged();
//                        }
//                    }
//                }
//            }
//        });
//    }


    @OnClick({R.id.item_declare_img_single, R.id.item_declare_video_img})
    public void onlyImgClick(View view) {
        if (declareBean == null || !TextUtils.isEmpty(declareBean.getVideoUrl())
                || !ListUtils.isListValued(declareBean.getImageList())
                || declareBean.getImageList().get(0) == null || TextUtils.isEmpty(declareBean.getImageList().get(0).getImageUrl())) {
            return;
        }
        String path = UrlUtils.linkUrls(Constances.ST_BASE_URL, declareBean.getImageList().get(0).getImageUrl());
        String type = (path.endsWith(".gif") || path.endsWith(".GIF")) ? "image/gif" : "image";
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        intent.putExtra("type", 1);
        ArrayList<LocalMedia> list = new ArrayList<>();
        list.add(new LocalMedia(path, "", type));
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, list);
        intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
        context.startActivity(intent);
    }

    private void initView(List<ImageUr> dataImgs) {
        //  if (dataImgs.size() == 4) {
        //      manager = new GridLayoutManager(context, 2);
        //  } else {
        manager = new GridLayoutManager(context, 3);
        //  }

        pic_list.setItemAnimator(new DefaultItemAnimator());
//        ((NoAlphaItemAnimator)pic_list.getItemAnimator()).setSupportsChangeAnimations(false);
//        pic_list.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题


        pic_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        if (adapter == null) {
            // new UiListMarginUtils().setMargin(context, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
            adapter = new PicAdapter(context, dataImgs);
        } else {
            adapter.setData(dataImgs);
        }
        pic_list.setAdapter(adapter);
    }

    @OnClick(value = {R.id.item_declare_pic_img1, R.id.item_declare_pic_img2,
            R.id.item_declare_pic_img4, R.id.item_declare_pic_img5})
    public void imgClick(View view) {
        Intent intent = new Intent(context, PictureExternalPreviewActivity.class);
        switch (view.getId()) {
            case R.id.item_declare_pic_img1:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
                break;
            case R.id.item_declare_pic_img2:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 1);
                break;
            case R.id.item_declare_pic_img4:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 2);
                break;
            case R.id.item_declare_pic_img5:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 3);
                break;

        }
        List<LocalMedia> images = new ArrayList<LocalMedia>();
        for (ImageUr imageUr : contentImage) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(Constances.ST_BASE_URL + imageUr.getImageUrl());
            images.add(localMedia);
        }

        intent.putExtra("type", 1);
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) images);
        context.startActivity(intent);
    }

    private void initImgView(final String path) {
        Glide.with(context)
                .load(path)
                .asBitmap()//强制Glide返回一个Bitmap对象
                .centerCrop()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) video_img.getLayoutParams();
                        if (height > width) {
                            if (height > UIUtils.dip2px(context, 240)) {
                                params.width = UIUtils.dip2px(context, 140);
                                params.height = UIUtils.dip2px(context, 240);
                            } else {
                                params.height =  height ;
                                params.width =  width ;

                            }
                        } else if (height < width) {
                            if (width > UIUtils.dip2px(context, 240)) {
                                params.height = UIUtils.dip2px(context, 140);
                                params.width = UIUtils.dip2px(context, 240);
                            } else {
                                params.height =  height ;
                                params.width =  width ;
                            }
                        } else {
                            JLog.e("-----initImgView---width = " + width + "---------height = " + height);
                            if (height > UIUtils.dip2px(context, 140)) {
                                params.height = UIUtils.dip2px(context, 140);
                                params.width = UIUtils.dip2px(context, 140);
                            } else {
                                params.height =  height ;
                                params.width =  width ;
                            }
                        }
                        video_img.setLayoutParams(params);
//                        itemOnlyImg.setImageBitmap(bitmap);
                        Glide.with(context)
                                .load(path)
                                .error(com.luck.picture.lib.R.drawable.icon_def_1_1)
                                .into(video_img);
                    }
                });
    }
}
